package com.chuhe.starry.dao;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chuhe.common.domain.entity.*;
import com.chuhe.common.domain.enums.*;
import com.chuhe.common.domain.query.UserContactQuery;
import com.chuhe.common.domain.vo.req.AdminLoadUserReq;
import com.chuhe.common.domain.vo.req.ApplyAddReq;
import com.chuhe.common.domain.vo.resp.SysSettingResp;
import com.chuhe.common.domain.vo.resp.UserContactVo;
import com.chuhe.common.domain.vo.resp.loadContactResp;
import com.chuhe.common.utils.RedisComponet;
import com.chuhe.common.utils.StringTools;
import com.chuhe.starry.mapper.UserContactMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.PropertySource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Date;

/**
 * <p>
 * 联系人 服务实现类
 * </p>
 *
 * @author 张楚河
 * @since 2025-05-11
 */
@Service
public class UserContactDao extends ServiceImpl<UserContactMapper, UserContact> {
    @Autowired
    private UserContactMapper userContactMapper;
    @Autowired
    private RedisComponet redisComponet;
    @Autowired
    private ChatSessionDao chatSessionDao;
    @Autowired
    private ChatSessionUserDao chatSessionUserDao;
    @Autowired
    private ChatMessageDao chatMessageDao;

    /**
     * 查询用户联系人
     * @Author: 楚河
     * @Date: 2025-05-11 16:22
     */
    public List<String> selectContactList(UserContact userContact) {
        List<UserContact> contactList = lambdaQuery()
                .eq(UserContact::getUserId, userContact.getUserId())
                .eq(UserContact::getStatus, userContact.getStatus())
                .list();
        return contactList.stream()
                .map(item -> item.getContactId())
                .collect(Collectors.toList());
    }
    /**
     * 查询该联系人的群聊
     * @Author: 楚河
     * @Date: 2025-05-14 19:22
     */
    public UserContact getUserContactByUserId(String userId, String groupId) {
        return lambdaQuery()
                .eq(UserContact::getUserId, userId)
                .eq(UserContact::getContactId, groupId)
                .one();
    }
    /**
     * 查询在群用户数量
     * @Author: 楚河
     * @Date: 2025-05-14 19:45
     */
    public Integer getOnGroupUserCount(String groupId) {
        return lambdaQuery()
                .eq(UserContact::getContactId, groupId)
                .count();
    }
    /**
     * 查询在群组内的用户联系人
     * @Author: 楚河
     * @Date: 2025-05-14 20:17
     */
    public List<UserContactVo> getOnGroupUserContact(String userContactId) {
        return userContactMapper.getOnGroupUserContact(userContactId);
    }
    /**
     * 根据用户id以及联系人id查询是否为好友  关系
     * @Author: 楚河
     * @Date: 2025-05-15 22:54
     */
    public UserContact selectByUserIdAndContactId(String userId, String contactId) {
        return lambdaQuery()
                .eq(UserContact::getUserId, userId)
                .eq(UserContact::getContactId, contactId)
                .one();
    }
    /**
     * 获取群组人数
     * @Author: 楚河
     * @Date: 2025-05-17 11:01
     */
    public Integer getOnGroupCount(UserContact userContact) {
        return lambdaQuery()
                .eq(UserContact::getContactId, userContact.getContactId())
                .eq(UserContact::getStatus, userContact.getStatus())
                .count();
    }
    /**
     * 查询联系人
     * @Author: 楚河
     * @Date: 2025-05-17 13:55
     */
    public List<loadContactResp> findUserOrGroup(UserContact userContact) {
        List<UserContact> collect = lambdaQuery()
                .eq(UserContact::getUserId, userContact.getUserId())
                .eq(UserContact::getContactId, userContact.getContactType())
                .list()
                .stream()
                .filter(contact -> {
                    return contact.getStatus().equals(UserContactStatusEnum.FRIEND.getStatus())
                            || contact.getStatus().equals(UserContactStatusEnum.BLACKLIST_BE.getStatus())
                            || contact.getStatus().equals(UserContactStatusEnum.DEL_BE.getStatus());
                })
                .sorted(Comparator.comparing(UserContact::getLastUpdateTime, Comparator.nullsLast(Comparator.reverseOrder())))
                .collect(Collectors.toList());

        // 将 UserContact 列表转换为 LoadContactResp 列表
        return collect.stream()
                .map(contact -> {
                    loadContactResp resp = new loadContactResp();
                    // 假设 LoadContactResp 有对应的 setter 方法
                    resp.setUserId(contact.getUserId());
                    resp.setContactId(contact.getContactId());
                    resp.setStatus(contact.getStatus());
                    resp.setLastUpdateTime(contact.getLastUpdateTime());
                    // 根据需要添加其他属性的映射
                    return resp;
                })
                .collect(Collectors.toList());
    }
    /**
     * 删除联系人
     * @Author: 楚河
     * @Date: 2025-05-17 16:55
     */
    public void delByUserIdAndContactId(String userId, String contactId) {
        LambdaQueryWrapper<UserContact> wrapperRequest = new LambdaQueryWrapper<>();
        wrapperRequest.eq(UserContact::getUserId, userId).eq(UserContact::getContactId, contactId);
        this.remove(wrapperRequest);
        LambdaQueryWrapper<UserContact> wrapperReceive = new LambdaQueryWrapper<>();
        wrapperReceive.eq(UserContact::getUserId, contactId).eq(UserContact::getContactId, userId);
        this.remove(wrapperReceive);
    }
    /**
     * 修改为已删除
     * @Author: 楚河
     * @Date: 2025-05-17 17:05
     */
    public void updateByUserIdAndContactId(UserContact userContact, String userId, String contactId) {
        lambdaUpdate()
                .eq(UserContact::getUserId,userId)
                .eq(UserContact::getContactId, contactId)
                .set(UserContact::getStatus,userContact.getStatus())
                .update();
    }
    /**
     * 更新联系人状态
     * @Author: 楚河
     * @Date: 2025-05-17 17:22
     */
    public void updateContactStatus(String userId, String contactId, Integer status) {
        lambdaUpdate()
                .eq(UserContact::getUserId,userId)
                .eq(UserContact::getContactId,contactId)
                .set(UserContact::getStatus,status)
                .update();
    }
    /**
     * 删除联系人群组
     * @Author: 楚河
     * @Date: 2025-05-18 14:35
     */
    public void delGroup(String groupId) {
        lambdaUpdate()
                .eq(UserContact::getContactId,groupId)
                .eq(UserContact::getContactType, UserContactTypeEnum.GROUP.getType())
                .set(UserContact::getStatus, UserContactStatusEnum.DEL.getStatus())
                .update();

    }
    /**
     * 查询群组联系人
     * @Author: 楚河
     * @Date: 2025-05-18 14:40
     */
    public List<UserContact> selectGroupContactList(String groupId, Integer type) {
        return lambdaQuery()
                .eq(UserContact::getContactId, groupId)
                .eq(UserContact::getContactType, type)
                .list();
    }
    /**
     * 创建机器人好友
     * @Author: 楚河
     * @Date: 2025-05-21 19:18
     */
    @Transactional
    public void addContact4Robot(String userId) {
        Date curDate = new Date();

        //获取系统设置...
        SysSettingResp sysSetting = redisComponet.getSysSetting();

        //添加机器人好友...
        UserContact UserContactBuild = UserContact.builder()
                .userId(userId)
                .contactId(sysSetting.getRobotUid())
                .contactType(UserContactTypeEnum.USER.getType())
                .createTime(curDate)
                .status(UserContactStatusEnum.FRIEND.getStatus())
                .lastUpdateTime(LocalDateTime.now())
                .build();
        save(UserContactBuild);

        //添加会话信息...
        String sessionId = StringTools.getChatSessionId4User(new String[]{userId, sysSetting.getRobotUid()});
        ChatSession ChatSessionBuild = ChatSession.builder()
                .lastMessage(sysSetting.getRobotWelcome())
                .sessionId(sessionId)
                .lastReceiveTime(curDate.getTime()).build();
        chatSessionDao.save(ChatSessionBuild);

        ChatSessionUser ChatSessionUserBuild = ChatSessionUser.builder()
                .userId(userId)
                .contactId(sysSetting.getRobotUid())
                .contactName(sysSetting.getRobotNickName())
                .sessionId(sessionId).build();
        chatSessionUserDao.save(ChatSessionUserBuild);

        //增加聊天消息...
        ChatMessage ChatMessageBuild = ChatMessage.builder()
                .sessionId(sessionId)
                .messageType(MessageTypeEnum.CHAT.getType())
                .messageContent(sysSetting.getRobotWelcome())
                .sendUserId(sysSetting.getRobotUid())
                .sendUserNickName(sysSetting.getRobotNickName())
                .sendTime(curDate.getTime())
                .contactId(userId)
                .contactType(UserContactTypeEnum.USER.getType())
                .status(MessageStatusEnum.SENDED.getStatus()).build();
        chatMessageDao.save(ChatMessageBuild);
    }

    /**
     * 获取群聊人员数量
     * @Author: 楚河
     * @Date: 2025-05-23 12:21
     */
    public Integer selectGroupCount(String groupId) {
        return lambdaQuery()
                .eq(UserContact::getContactId, groupId)
                .eq(UserContact::getStatus, UserContactStatusEnum.FRIEND.getStatus())
                .count();
    }
    /**
     * 查询用户集合
     * @Author: 楚河
     * @Date: 2025-05-23 17:18
     */
    public List<UserContact> selectUserContactList(String contactId) {
        return lambdaQuery()
                .eq(UserContact::getContactId, contactId)
                .eq(UserContact::getContactType, UserContactTypeEnum.USER.getType())
                .eq(UserContact::getStatus, UserContactStatusEnum.FRIEND.getStatus())
                .list();
    }
    /**
     * 查询数量
     * @Author: 楚河
     * @Date: 2025-05-24 17:02
     */
    public Integer selectCount(UserContactQuery userContactQuery) {
        return lambdaQuery()
                .eq(UserContact::getUserId, userContactQuery.getUserId())
                .eq(UserContact::getContactType, userContactQuery.getContactType())
                .eq(UserContact::getContactId, userContactQuery.getContactId())
                .eq(UserContact::getStatus, userContactQuery.getStatus())
                .count();

    }
    /**
     * 根据id删除
     * @Author: 楚河
     * @Date: 2025-05-24 17:30
     */
    public Boolean deleteByUserIdAndContactId(String userId, String groupId) {
        LambdaQueryWrapper<UserContact> wrapperRequest = new LambdaQueryWrapper<>();
        wrapperRequest.eq(UserContact::getUserId, userId).eq(UserContact::getContactId, groupId);
        return this.remove(wrapperRequest);
    }
    /**
     * 查询数量
     * @Author: 楚河
     * @Date: 2025-05-24 17:34
     */
    public Integer selectCountById(UserContactQuery userContactQuery) {
        return lambdaQuery()
                .eq(UserContact::getContactId, userContactQuery.getContactId())
                .eq(UserContact::getStatus, userContactQuery.getStatus())
                .count();
    }
}
